package study.web;

import study.pojo.User;
import study.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserServiceImpl service=new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //获取用户输入的验证码
        String checkCode = req.getParameter("checkCode");

        //获取程序生成的验证码
        HttpSession session = req.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");

        //封装用户对象
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);

        /*2.调用Mybatis完成查询*/
        //  2.1获取SqlSessionFactory对象
/*        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);*/
        resp.setContentType("text/html;charset=utf-8");

        if(checkCodeGen.equals(checkCode)){
            //验证码错误
            req.setAttribute("register_msg","验证码错误！");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);

            return;
        }
        boolean flag = service.register(user);

        if(flag){
            //注册成功
            req.setAttribute("login_msg","注册成功，请登录！");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else {
            //注册失败,跳转到注册页面
            req.setAttribute("register_msg","注册失败，用户名已存在！");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);


        }



    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
